package com.feiyi.app.activity;

import android.Manifest;
import android.app.ActionBar;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.ToastUtils;
import com.feiyi.app.R;
import com.feiyi.app.app.AppConstant;
import com.feiyi.app.base.BaseActivity;
import com.feiyi.app.bean.ChangeHeadBean;
import com.feiyi.app.bean.RegisterBean;
import com.feiyi.app.event.ChangeHeadEvent;
import com.feiyi.app.event.LoginEvent;
import com.feiyi.app.glideutils.GlideImgManager;
import com.feiyi.app.net.HttpMethods;
import com.feiyi.app.utils.Image2Base64Util;
import com.feiyi.app.utils.PhotoUtils;
import com.feiyi.app.utils.WindowUtils;
import com.google.common.base.MoreObjects;
import com.limxing.library.AlertView;
import com.limxing.library.OnConfirmeListener;

import org.greenrobot.eventbus.EventBus;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import de.hdodenhof.circleimageview.CircleImageView;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * 作者 : wlt
 * 创建时间:  2018-08-03
 * QQ : 1346947404
 * 邮箱:wanglt_android@163.com
 * 类说明:个人设置页面,包括昵称修改,绑定手机号,头像修改,生日修改,性别信息,退出登录等功能
 * In me the tiger sniffs the rose
 */

public class PersonSettingActivity extends BaseActivity implements OnConfirmeListener {

    Unbinder unbinder;

    @BindView(R.id.rl_bind_telephone)
    RelativeLayout rl_bind_telephone;
    @BindView(R.id.rl_head_img)
    RelativeLayout rl_head_img;
    @BindView(R.id.iv_head_img)
    CircleImageView iv_head_img;
    @BindView(R.id.tv_birthday)
    TextView tv_birthday;
    @BindView(R.id.tv_sex)
    TextView tv_sex;
    @BindView(R.id.tv_username)
    TextView tvUsername;
    private AlertView alertview;
    private String head;
    private String uid;
    private String sid;
    private String birthday;
    private String sex;

    private PopupWindow SelectPicdialog;
    private PopupWindow sexPopupwindow;
    private static final String TAG = "mainsetting";

    private static final int CODE_GALLERY_REQUEST = 0xa0;
    private static final int CODE_CAMERA_REQUEST = 0xa1;
    private static final int CODE_RESULT_REQUEST = 0xa2;
    private static final int CAMERA_PERMISSIONS_REQUEST_CODE = 0x03;
    private static final int STORAGE_PERMISSIONS_REQUEST_CODE = 0x04;

    private File fileUri = new File(Environment.getExternalStorageDirectory().getPath() + "/photo.jpg");
    private File fileCropUri = new File(Environment.getExternalStorageDirectory().getPath() + "/crop_photo.jpg");
    private Uri imageUri;
    private Uri cropImageUri;
    private String picturePath = "";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settings_mine);
        unbinder = ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        uid = spUtils.getString(AppConstant.UID);
        sid = spUtils.getString(AppConstant.SID);
        sex = spUtils.getString(AppConstant.SEX);
        birthday = spUtils.getString(AppConstant.BIRTHDAY);
        if (null != birthday && !birthday.isEmpty()){
            tv_birthday.setText(birthday);
        }
        if (null == sex || sex.isEmpty()){
            tv_sex.setText("男");
        }else if (sex.equals("1")){
            tv_sex.setText("男");
        }else {
            tv_sex.setText("女");
        }
        tvUsername.setText(spUtils.getString(AppConstant.NAME));
        head = spUtils.getString(AppConstant.AVATAR);
        if (null == head || head.isEmpty()){
            iv_head_img.setImageResource(R.mipmap.icon_register_defult_head);
        }else {
            GlideImgManager.loadUserImage(activity,head,iv_head_img);
        }
    }

    @OnClick({R.id.btn_logout,R.id.rl_birthday,R.id.rl_head_img,R.id.rl_sex})
    public void onClick(View view){

        switch (view.getId()){
            case R.id.btn_logout:
                logout();
                EventBus.getDefault().post(new LoginEvent(new RegisterBean()));
                finish();
                break;
            case R.id.rl_birthday:
                alertview = new AlertView("请选择日期", this, 1930, 2100, this);
                alertview.show();
                break;
            case R.id.rl_head_img:
                if (SelectPicdialog == null) {
                    ShowSelectPicDialog(view.getWidth());
                }
                WindowUtils.setAlpha(this,0.7f);
                SelectPicdialog.showAtLocation(getWindow().getDecorView(), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                break;
            case R.id.rl_sex:
                if (sexPopupwindow == null) {
                    ShowSelectSexDialog(view.getWidth());
                }
                WindowUtils.setAlpha(this,0.7f);
                sexPopupwindow.showAtLocation(getWindow().getDecorView(), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                break;
        }

    }

    private void logout(){
        spUtils.remove(AppConstant.SID);//固定保存
        spUtils.remove(AppConstant.UID);//固定保存
        spUtils.remove(AppConstant.COLLECTION_NUM);//收藏的商品数量
        spUtils.remove(AppConstant.EMAIL);//用户邮箱
        spUtils.remove(AppConstant.ID);//用户id,靠这个id去进行各种操作
        spUtils.remove(AppConstant.NAME);//用户名,显示的用户名
        spUtils.remove(AppConstant.AWAIT_PAY);//待付款数量
        spUtils.remove(AppConstant.AWAIT_SHIP);//待发货数量
        spUtils.remove(AppConstant.FINISHED);//已完成订单数量
        spUtils.remove(AppConstant.SHIPPED);//已收货数量
        spUtils.remove(AppConstant.RANK_LEVEL);//积分
        spUtils.remove(AppConstant.RANK_NAME);//用户等级名称
        spUtils.remove(AppConstant.AVATAR);//用户头像
        spUtils.remove(AppConstant.BIRTHDAY);//用户头像
        spUtils.remove(AppConstant.SEX);//用户头像
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
    }

    @Override
    public void result(String s) {
        String[] strs = s.split("年");
        String year1 = strs[0].toString();
        String year2 = strs[1].toString();
        String[] strs2 = year2.split("月");
        String yue1 = strs2[0].toString();
        String yue2 = strs2[1].toString();
        String ri = yue2.substring(0, yue2.length() - 1);
        if (Integer.parseInt(yue1) < 10) {
            yue1 = 0 + yue1;
        }
        if (Integer.parseInt(ri) < 10) {
            ri = 0 + ri;
        }
        s = year1 + "年" + yue1 + "月" + ri + "日";
        tv_birthday.setText(s);
        checkBirthday(s);
    }
    private void checkBirthday(final String s){
        FormBody.Builder builder = new FormBody.Builder();
        builder.add("uid",uid);
        builder.add("sid",sid);
        builder.add("birthday",s);
        RequestBody body = builder.build();
        HttpMethods.getInstance().info.updateBirthday(AppConstant.UPDATEPERSON,body)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<RegisterBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(RegisterBean registerBean) {
                        if (registerBean.getStatus().getSucceed() == 1){
                            ToastUtils.showShort("生日修改成功");
                            spUtils.put(AppConstant.BIRTHDAY,s);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e(TAG, "onError: "+e.toString());
                        ToastUtils.showShort("修改生日失败");
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
    private Handler handle = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                Bundle bundle = msg.getData();
                String url = bundle.getString("url");
                Log.e(TAG, "handleMessage: "+url );
                    ToastUtils.showShort("头像修改成功");
                spUtils.put(AppConstant.AVATAR,url);
                EventBus.getDefault().post(new ChangeHeadEvent(url));
                GlideImgManager.loadUserImage(activity,url,iv_head_img);
            } else if (msg.what == 1) {

                    ToastUtils.showShort("头像修改失败");

            }
        }
    };

    // 显示相片选择方式对话框
    private void ShowSelectPicDialog(int width) {
        View root = this.getLayoutInflater().inflate(R.layout.select_pic_dialog, null);
        SelectPicdialog = new PopupWindow(root, width, ActionBar.LayoutParams.WRAP_CONTENT);

        // 为确认按钮添加事件
        TextView takePhoto = (TextView) root.findViewById(R.id.btn_take_photo);




        takePhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                SelectPicdialog.dismiss();
                autoObtainCameraPermission();
            }
        });
        TextView pickPhoto = (TextView) root.findViewById(R.id.btn_pick_photo);

        pickPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                SelectPicdialog.dismiss();
                autoObtainStoragePermission();
            }
        });
        TextView cancel = (TextView) root.findViewById(R.id.btn_cancel);

        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                SelectPicdialog.dismiss();
            }
        });
        SelectPicdialog.setFocusable(true);
        SelectPicdialog.setOutsideTouchable(true);
        SelectPicdialog.setBackgroundDrawable(new BitmapDrawable(getResources()));
        SelectPicdialog.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowUtils.setAlpha(PersonSettingActivity.this,1f);
            }
        });
    }

    /**
     * 自动获取相机权限
     */
    private void autoObtainCameraPermission() {

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {

                ToastUtils.showShort("您已经拒绝过一次");
            }
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE}, CAMERA_PERMISSIONS_REQUEST_CODE);
        } else {//有权限直接调用系统相机拍照
            if (hasSdcard()) {
                imageUri = Uri.fromFile(fileUri);
                //通过FileProvider创建一个content类型的Uri
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    imageUri = FileProvider.getUriForFile(PersonSettingActivity.this, "com.cn.xty.news.fileprovider", fileUri);
                }
                PhotoUtils.takePicture(this, imageUri, CODE_CAMERA_REQUEST);
            } else {
                ToastUtils.showShort("设备没有SD卡！");
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        switch (requestCode) {
            //调用系统相机申请拍照权限回调
            case CAMERA_PERMISSIONS_REQUEST_CODE: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    if (hasSdcard()) {
                        imageUri = Uri.fromFile(fileUri);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
                            imageUri = FileProvider.getUriForFile(PersonSettingActivity.this, "com.trs.xzw.fileprovider", fileUri);//通过FileProvider创建一个content类型的Uri
                        PhotoUtils.takePicture(this, imageUri, CODE_CAMERA_REQUEST);
                    } else {
                        ToastUtils.showShort("设备没有SD卡！");
                    }
                } else {

                    ToastUtils.showShort("请允许打开相机！！");
                }
                break;


            }
            //调用系统相册申请Sdcard权限回调
            case STORAGE_PERMISSIONS_REQUEST_CODE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    PhotoUtils.openPic(this, CODE_GALLERY_REQUEST);
                } else {

                    ToastUtils.showShort("请允许操作SD卡！！");
                }
                break;
            default:
        }
    }


    /**
     * 自动获取sdk权限
     */

    private void autoObtainStoragePermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSIONS_REQUEST_CODE);
        } else {
            PhotoUtils.openPic(this, CODE_GALLERY_REQUEST);
        }

    }
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri
                .getAuthority());
    }

    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri
                .getAuthority());
    }

    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri
                .getAuthority());
    }

    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri
                .getAuthority());
    }
    private int output_X = 480;
    private int output_Y = 480;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == CODE_GALLERY_REQUEST) {//调用相册完成回调
            if (hasSdcard()) {
                cropImageUri = Uri.fromFile(fileCropUri);
                if (data != null) {
                    Uri newUri = Uri.parse(PhotoUtils.getPath(this, data.getData()));
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
                        newUri = FileProvider.getUriForFile(this, "com.trs.xzw.fileprovider", new File(newUri.getPath()));
                    PhotoUtils.cropImageUri(this, newUri, cropImageUri, 1, 1, output_X, output_Y, CODE_RESULT_REQUEST);
                }
            } else {
                Toast.makeText(PersonSettingActivity.this, "设备没有SD卡！", Toast.LENGTH_SHORT).show();
            }
        }
        if (requestCode == CODE_CAMERA_REQUEST) {//拍照完成回调
            cropImageUri = Uri.fromFile(fileCropUri);
            PhotoUtils.cropImageUri(this, imageUri, cropImageUri, 1, 1, output_X, output_Y, CODE_RESULT_REQUEST);
        }
        if (requestCode == CODE_RESULT_REQUEST) {

            Bitmap bitmap = PhotoUtils.getBitmapFromUri(cropImageUri, this);
            if (bitmap != null) {

                iv_head_img.setImageURI(cropImageUri);
                picturePath = fileCropUri.getAbsolutePath();
                setImage2(picturePath);
            }
        }
    }


    private void setImage2(String picturePath) {
        String base64 = Image2Base64Util.imageToBase64(picturePath);
        Log.e(TAG, "setImage2: "+base64 );
        FormBody.Builder builder = new FormBody.Builder();
        builder.add("uid",uid);
        builder.add("sid",sid);
        builder.add("avatar","data:image/jpeg;base64,"+base64);
        RequestBody body = builder.build();
        HttpMethods.getInstance().info.updateHead(AppConstant.UPDATEHEAD,body)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ChangeHeadBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(ChangeHeadBean yanZhengBean) {
                        Log.e(TAG, "onNext: "+yanZhengBean.toString() );
                        Message message = new Message();
                        if (yanZhengBean.getStatus().getSucceed().equals("1")){
                            String image = yanZhengBean.getData().getAvatar();
                            String nickName = spUtils.getString(AppConstant.NAME);
                            Bundle bundle = new Bundle();
                            bundle.putString("url", image);
                            bundle.putString("nickname", nickName);
                            message.setData(bundle);
                            message.what = 0;
                            handle.sendMessage(message);
                        }else {
                            handle.sendEmptyMessage(1);
                        }

                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e(TAG, "onError: "+e.toString() );
                        dispose();
                    }

                    @Override
                    public void onComplete() {

                    }
                });


    }

    /**
     * 检查设备是否存在SDCard的工具方法
     */
    public static boolean hasSdcard() {
        String state = Environment.getExternalStorageState();
        return state.equals(Environment.MEDIA_MOUNTED);
    }
    // 显示相片选择方式对话框
    private void ShowSelectSexDialog(int width) {
        View root = this.getLayoutInflater().inflate(R.layout.select_sex_dialog, null);
        sexPopupwindow = new PopupWindow(root, width, ActionBar.LayoutParams.WRAP_CONTENT);

        RadioGroup radioGroup = root.findViewById(R.id.radiogroup);
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.rb_1){

                        checkSex("1");

                }else if (checkedId == R.id.rb_2){

                        checkSex("2");

                }
            }
        });


        TextView cancel =  root.findViewById(R.id.tv_sex_cancle);

        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                sexPopupwindow.dismiss();
            }
        });
        sexPopupwindow.setFocusable(true);
        sexPopupwindow.setOutsideTouchable(true);
        sexPopupwindow.setBackgroundDrawable(new BitmapDrawable(getResources()));
        sexPopupwindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowUtils.setAlpha(PersonSettingActivity.this,1f);
            }
        });
    }

    private void checkSex(final String s){
        FormBody.Builder builder = new FormBody.Builder();
        builder.add("uid",uid);
        builder.add("sid",sid);
        builder.add("sex",s);
        RequestBody body = builder.build();
        HttpMethods.getInstance().info.updateSex(AppConstant.UPDATEPERSON,body)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<RegisterBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(RegisterBean registerBean) {
                        if (registerBean.getStatus().getSucceed() == 1){

                            spUtils.put(AppConstant.SEX,s);
                            if (s.equals("1")){
                                tv_sex.setText("男");
                            }else {
                                tv_sex.setText("女");
                            }
                            sexPopupwindow.dismiss();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e(TAG, "onError: "+e.toString());
                        ToastUtils.showShort("修改性别失败");
                        sexPopupwindow.dismiss();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

}
